#include "treeviewmodel.h"

int nameRole = Qt::UserRole+1;
int iconRole = Qt::UserRole+2;

TreeViewModel::TreeViewModel()
{
    auto node = new TreeNode();
    node->setData(nameRole,"parent 1");
    node->setData(iconRole,"parent icon1");
    addEntryNode(node);

    auto subNode = new TreeNode();
    subNode->setData(nameRole,"child 1");
    subNode->setData(iconRole,"child icon1");
    addEntryNode(subNode,node);

    subNode = new TreeNode();
    subNode->setData(nameRole,"child 2");
    subNode->setData(iconRole,"child icon2");
    addEntryNode(subNode,node);

    node = new TreeNode();
    node->setData(nameRole,"parent 2");
    node->setData(iconRole,"parent icon2");
    addEntryNode(node);

    mRoleNames[nameRole] = QByteArrayLiteral("name");
    mRoleNames[iconRole] = QByteArrayLiteral("icon");
}

QModelIndex TreeViewModel::index(int row, int column, const QModelIndex &parent) const
{
    if(!parent.isValid())
    {
        if((row >= 0) && (row < mRootEntrys.size()))
        {
            return createIndex(row,column,mRootEntrys.at(row));
        }
    }
    else
    {
        TreeNodePtr parentNode = (TreeNodePtr)parent.internalPointer();
        return createIndex(row,column,parentNode->childs[row]);
    }
    return QModelIndex();
}

QModelIndex TreeViewModel::parent(const QModelIndex &index) const
{
    TreeNodePtr node = (TreeNodePtr)index.internalPointer();
    if(node->parent() == NULL)
    {
        return QModelIndex();
    }
    else
    {
        return createIndex(0,1,node->parent());
    }
}

int TreeViewModel::rowCount(const QModelIndex &parent) const
{
    if(parent.isValid())
    {
        TreeNodePtr parentNode = (TreeNodePtr)parent.internalPointer();
        return parentNode->childs.size();
    }
    return mRootEntrys.size();
}

int TreeViewModel::columnCount(const QModelIndex &parent) const
{
    return 1;
}

QVariant TreeViewModel::data(const QModelIndex &index, int role) const
{
    TreeNodePtr node = (TreeNodePtr)index.internalPointer();
    return node->data(role);
}

QHash<int, QByteArray> TreeViewModel::roleNames() const
{
    return mRoleNames;
}

void TreeViewModel::addEntryNode(TreeNodePtr node, TreeNodePtr parent)
{
    if(parent == NULL)
    {
        mRootEntrys.append(node);
    }
    else
    {
        node->setParent(parent);
        parent->appendNode(node);
    }
}
